<template>
  <div class="user-activity-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="我的活动"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="content">
      <!-- 活动统计卡片 -->
      <div class="stats-section">
        <div class="stats-card">
          <div class="stats-item">
            <van-icon name="eye-o" size="24" color="#1989fa" />
            <div class="stats-value">{{ userStats.browseCount || 0 }}</div>
            <div class="stats-label">浏览</div>
          </div>
          <div class="stats-item">
            <van-icon name="star" size="24" color="#ff6000" />
            <div class="stats-value">{{ userStats.favoriteCount || 0 }}</div>
            <div class="stats-label">收藏</div>
          </div>
          <div class="stats-item">
            <van-icon name="like-o" size="24" color="#ee0a24" />
            <div class="stats-value">{{ userStats.ratingCount || 0 }}</div>
            <div class="stats-label">评分</div>
          </div>
          <div class="stats-item">
            <van-icon name="shopping-cart-o" size="24" color="#07c160" />
            <div class="stats-value">{{ userStats.makeCount || 0 }}</div>
            <div class="stats-label">制作</div>
          </div>
        </div>
      </div>

      <!-- 标签页 -->
      <van-tabs v-model="activeTab" animated sticky>
        <van-tab title="最近浏览">
          <div class="tab-content">
            <van-empty v-if="browseLoading" description="加载中...">
              <template #image>
                <van-loading type="spinner" size="36" />
              </template>
            </van-empty>

            <van-empty
              v-else-if="browseHistory.length === 0"
              description="暂无浏览记录"
            />

            <template v-else>
              <div class="history-list">
                <div
                  v-for="item in browseHistory"
                  :key="item.id"
                  class="history-item"
                  @click="navigateToRecipe(item.recipeId)"
                >
                  <div class="item-image">
                    <img
                      :src="item.recipe?.imageUrl || defaultImage"
                      :alt="item.recipe?.name"
                    />
                  </div>
                  <div class="item-content">
                    <div class="item-title">
                      {{ item.recipe?.name || "未知食谱" }}
                    </div>
                    <div class="item-meta">
                      <div class="view-time">
                        <van-icon name="clock-o" />
                        <span>{{ formatDate(item.viewTime) }}</span>
                      </div>
                      <div class="view-duration">
                        <van-icon name="play-circle-o" />
                        <span>{{ formatDuration(item.viewDuration) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="view-more" v-if="browseHistory.length > 0">
                <van-button round size="small" to="/user/browse-history"
                  >查看更多</van-button
                >
              </div>
            </template>
          </div>
        </van-tab>

        <van-tab title="我的评分">
          <div class="tab-content">
            <van-empty v-if="ratingLoading" description="加载中...">
              <template #image>
                <van-loading type="spinner" size="36" />
              </template>
            </van-empty>

            <van-empty
              v-else-if="ratingHistory.length === 0"
              description="暂无评分记录"
            />

            <template v-else>
              <div class="rating-list">
                <div
                  v-for="item in ratingHistory"
                  :key="item.id"
                  class="rating-item"
                  @click="navigateToRecipe(item.recipeId)"
                >
                  <div class="item-image">
                    <img
                      :src="item.recipe?.imageUrl || defaultImage"
                      :alt="item.recipe?.name"
                    />
                    <div class="rating-badge">
                      <span>{{ item.rating }}</span>
                      <van-icon name="star" color="#ff6000" />
                    </div>
                  </div>
                  <div class="item-content">
                    <div class="item-title">
                      {{ item.recipe?.name || "未知食谱" }}
                    </div>
                    <div class="item-comment" v-if="item.comment">
                      {{ item.comment }}
                    </div>
                    <div class="item-meta">
                      <div class="rating-time">
                        <van-icon name="clock-o" />
                        <span>{{ formatDate(item.createTime) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </van-tab>

        <van-tab title="收藏食谱">
          <div class="tab-content">
            <van-empty v-if="collectionLoading" description="加载中...">
              <template #image>
                <van-loading type="spinner" size="36" />
              </template>
            </van-empty>

            <van-empty
              v-else-if="collections.length === 0"
              description="暂无收藏记录"
            />

            <template v-else>
              <div class="collection-list">
                <div
                  v-for="item in collections"
                  :key="item.id"
                  class="collection-item"
                  @click="navigateToRecipe(item.id)"
                >
                  <div class="item-image">
                    <img
                      :src="item.imageUrl || defaultImage"
                      :alt="item.name"
                    />
                  </div>
                  <div class="item-content">
                    <div class="item-title">{{ item.name || "未知食谱" }}</div>
                    <div class="item-meta">
                      <div class="collection-rating" v-if="item.rating">
                        <van-rate
                          v-model="item.rating"
                          readonly
                          size="12"
                          allow-half
                        />
                        <span>{{ item.rating.toFixed(1) }}</span>
                      </div>
                      <div class="collection-time">
                        <van-icon name="clock-o" />
                        <span>{{ formatDate(item.collectionTime) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="view-more" v-if="collections.length > 0">
                <van-button round size="small" to="/user/favorites"
                  >查看更多</van-button
                >
              </div>
            </template>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { useUserStore } from "@/stores/userStore";
import {
  getUserCollections,
  getUserRatings,
  getRecipeRatings,
} from "@/api/recipe";
import {
  getBrowseHistoryList,
  getUserViewHistory,
  getUserInteractionStats,
  getUserStats,
} from "@/api/user";
import defaultImage from "@/assets/default-recipe.jpg";

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const activeTab = ref(0);
const userStats = ref({
  browseCount: 0,
  favoriteCount: 0,
  ratingCount: 0,
  makeCount: 0,
});

const browseHistory = ref([]);
const ratingHistory = ref([]);
const collections = ref([]);

const browseLoading = ref(false);
const ratingLoading = ref(false);
const collectionLoading = ref(false);

// 获取用户ID
const userId = computed(() => userStore.userId);

// 获取用户统计信息
const getUserStats = async () => {
  try {
    const res = await getUserStats(userId.value);

    if (res.code === 200 && res.data) {
      userStats.value = res.data;
    } else {
      showToast("获取统计信息失败");
    }
  } catch (error) {
    console.error("获取用户统计信息失败", error);
    showToast("获取统计信息失败");
  }
};

// 加载浏览历史
const loadBrowseHistory = async () => {
  if (browseLoading.value) return;
  try {
    browseLoading.value = true;
    // 获取最近5条浏览记录
    const res = await getUserViewHistory(userId.value, 1, 5);

    if (res.code === 200 && res.data) {
      if (res.data.records) {
        browseHistory.value = res.data.records;
      }
    } else {
      showToast("获取浏览记录失败");
    }
  } catch (error) {
    console.error("加载浏览历史失败", error);
  } finally {
    browseLoading.value = false;
  }
};

// 加载评分历史
const loadRatingHistory = async () => {
  if (ratingLoading.value) return;
  try {
    ratingLoading.value = true;
    const res = await getUserRatings(userId.value);
    if (res.code === 200) {
      ratingHistory.value = res.data.list;
    } else {
      showToast("获取评分历史失败");
    }
  } catch (error) {
    console.error("获取评分历史异常:", error);
    showToast("获取评分历史失败");
  } finally {
    ratingLoading.value = false;
  }
};

// 加载收藏列表
const loadCollections = async () => {
  if (collectionLoading.value) return;
  try {
    collectionLoading.value = true;
    const res = await getUserCollections(userId.value, 1, 5);

    if (res.code === 200 && res.data) {
      if (res.data.records) {
        collections.value = res.data.records;
      }
    } else {
      showToast("获取收藏列表失败");
    }
  } catch (error) {
    console.error("加载收藏列表失败", error);
  } finally {
    collectionLoading.value = false;
  }
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 格式化浏览时长
const formatDuration = (seconds) => {
  if (!seconds) return "0秒";
  if (seconds < 60) return `${seconds}秒`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return remainingSeconds > 0
    ? `${minutes}分${remainingSeconds}秒`
    : `${minutes}分钟`;
};

// 跳转到食谱详情
const navigateToRecipe = (id) => {
  router.push(`/recipe/${id}`);
};

// 加载对应标签页数据
const loadTabData = (index) => {
  switch (index) {
    case 0:
      if (browseHistory.value.length === 0) {
        loadBrowseHistory();
      }
      break;
    case 1:
      if (ratingHistory.value.length === 0) {
        loadRatingHistory();
      }
      break;
    case 2:
      if (collections.value.length === 0) {
        loadCollections();
      }
      break;
  }
};

// 监听标签页变化
const handleTabChange = (index) => {
  loadTabData(index);
};

// 生命周期
onMounted(() => {
  getUserStats();
  loadTabData(activeTab.value);
});
</script>

<style scoped>
.user-activity-container {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-top: 46px;
}

.content {
  padding-bottom: 24px;
}

.stats-section {
  padding: 16px;
}

.stats-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stats-value {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
}

.stats-label {
  font-size: 12px;
  color: #969799;
}

.tab-content {
  padding: 16px;
}

.history-list,
.rating-list,
.collection-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item,
.rating-item,
.collection-item {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.item-image {
  width: 100px;
  height: 100px;
  position: relative;
  flex-shrink: 0;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.rating-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 2px 6px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 2px;
  font-size: 12px;
}

.item-content {
  flex: 1;
  padding: 12px;
  display: flex;
  flex-direction: column;
}

.item-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.item-comment {
  font-size: 14px;
  color: #646566;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-meta {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #969799;
}

.view-time,
.view-duration,
.rating-time,
.collection-time,
.collection-rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.collection-rating {
  display: flex;
  align-items: center;
  gap: 4px;
}

.view-more {
  text-align: center;
  margin-top: 16px;
}
</style>
